package cn.aoyu.test.util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName: ConcurrentRequestUtil
 * @Auther: xww
 * @Date: 2019/6/11 0011 16:50
 * @Description: 通过线程池、countDownLatch、Semaphore 来模拟并发量
 */
public abstract class BaseConcurrentRequestUtil {

	// 计算请求的次数
	public static AtomicInteger atomicInteger = new AtomicInteger(0);

	/**
	 * 并发量测试类工具
	 *
	 * @param requestTotal        总的请求个数
	 * @param concurrentThreadNum 同一时刻最大的并发线程的个数
	 */
	public void execute(int requestTotal, int concurrentThreadNum) throws InterruptedException {
		ExecutorService executorService = Executors.newCachedThreadPool();
		CountDownLatch countDownLatch = new CountDownLatch(requestTotal);
		Semaphore semaphore = new Semaphore(concurrentThreadNum);
		for (int i = 0; i < requestTotal; i++) {
			executorService.execute(() -> {
				try {
					semaphore.acquire();
					atomicInteger.addAndGet(1);
					executeMethod();
					semaphore.release();
				} catch (InterruptedException e) {
					System.out.println(e.getMessage());
				}
				countDownLatch.countDown();
			});
		}
		countDownLatch.await();
		executorService.shutdown();
	}


	/**
	 * 并发需要执行的代码
	 * 子类可以继承来处理业务逻辑
	 */
	public abstract void executeMethod();

}
